/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package threadserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Bryce
 */
public class ThreadServer {
    public static final int BUFFER_SIZE = 256;
    private static final int DEFAULT_PORT = 9090;
    public static int totalClients = 0;
    public static int concurrentClients = 0;
    
    private ClientLogger logger;
    
    private int port;
    private ServerSocket listeningSocket;
    
    public ThreadServer(int port, String fileName) {
        this.logger = new ClientLogger(fileName);
        Thread loggerThread = new Thread(logger);
        loggerThread.start();
        this.port = port;
        try {
            listeningSocket = new ServerSocket(this.port);
        } catch (IOException ex) {
            Logger.getLogger(ThreadServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void listenForClients() {
        while(true) {
            try {
                Socket connectionsocket = listeningSocket.accept();
                totalClients++;
                concurrentClients++;
                logger.addItem(new Date().getTime()+","+totalClients+","+concurrentClients+","+connectionsocket.getInetAddress().getHostAddress()+","+connectionsocket.getPort());
                Client client = new Client(connectionsocket,this.logger);
                Thread thread = new Thread(client);
                thread.start();
            } catch (IOException ex) {
                logger.addItem(new Date().getTime()+",Error accepting client");
            }
        }
    }
    
    public static void main(String[] args) {
        int port = DEFAULT_PORT;
        String fileName = null;
        if(args.length == 1) {
            port = Integer.parseInt(args[0]);
        }
        if(args.length == 2) {
            port = Integer.parseInt(args[0]);
            fileName = args[1];
        }
        ThreadServer threadServer = new ThreadServer(port, fileName);
        threadServer.listenForClients();
    }
    
}
